package com.event.core.config;

import com.event.common.face.IAnnotationHandle;
import com.event.core.context.AnnotationContext;
import com.event.core.parse.CacheableParse;
import com.event.core.parse.CacheableParseFactory;
import com.event.core.processor.AnnotationsEventProcessor;
import com.event.core.properties.AnnotationEventProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;

import javax.annotation.Resource;
import java.util.Map;

/*
 * @description 自动扫描注解配置
 * @author Bing
 * @date 2024/10/8 13:55
 **/
@Configuration
@ConditionalOnBean(AnnotationEventProperties.class)
public class AutoScanAnnotationConfig {
    /**
     * 注解处理器(有默认处理逻辑,但是事件依然可以传播到处理器，此处可以自行实现接口)
     */
    @Autowired(required = false)
    private IAnnotationHandle iAnnotationHandle;
    /**
     * 缓存解析器(可以自定义自己的缓存key规则，需要写具体实现并配置config.annotation.monitor.cacheableParseName)
     */
    @Autowired
    private Map<String, CacheableParse> cacheableParseMap;
    /**
     * 注解配置
     */
    @Resource
    private AnnotationEventProperties annotationEventProperties;

    /**
     * 注解上下文
     * @return
     */
    @Bean
    public AnnotationContext annotationContext() {
        AnnotationContext annotationContext = new AnnotationContext(annotationEventProperties, iAnnotationHandle);
        return annotationContext;
    }

    /**
     * 注解事件处理器
     * @param annotationContext
     * @return
     */
    @Bean
    public AnnotationsEventProcessor annotationsEventProcessor(AnnotationContext annotationContext) {
        return new AnnotationsEventProcessor(annotationContext);
    }

    /**
     * 缓存解析工厂
     * @return
     */
    @Bean
    public CacheableParseFactory cacheableParseFactory(){
        return new CacheableParseFactory(cacheableParseMap);
    }

    /**
     * 默认缓存解析器
     * @param cacheableParseFactory
     * @param annotationContext
     * @return
     */
    @Bean
    @DependsOn("annotationsEventProcessor")
    @Primary
    public CacheableParse getCacheableParse(CacheableParseFactory cacheableParseFactory,AnnotationContext annotationContext){
        CacheableParse cacheableParse = cacheableParseFactory.get(annotationEventProperties.getCacheableParseName());
        cacheableParse.init(annotationContext);
        return cacheableParse;
    }
}
